package leetcode.hot100;

import pojo.ListNode;

/**
 * 19. 删除链表的倒数第 N 个结点
 *
 * @author: yjf
 * @date: 2024/11/29
 */
public class LeetCode19 {

    public static ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null) {
            return null;
        }
        ListNode cur = head;
        int count = 0;
        while (cur != null) {
            count++;
            cur = cur.next;
        }
        if (count == n) {
            return head.next;
        }
        if (count == 1) {
            return head;
        }
        ListNode pre = head;
        cur = head.next;
        // 3个节点 删除n=1倒数第一个，则那到第二个节点
        for (int i = 1; i < count - n; i++) {
            pre = pre.next;
            cur = cur.next;
        }
        if (cur.next != null) {
            pre.next = cur.next;
        } else {
            pre.next = null;
        }
        return head;
    }

    public static void main(String[] args) {
        // head = [1,2,3,4,5], n = 2       =>       [1,2,3,5]
        ListNode head = new ListNode(1, new ListNode(2, new ListNode(3, new ListNode(4, new ListNode(5)))));
        ListNode listNode = removeNthFromEnd(head, 2);
        while (listNode != null) {
            System.out.println(listNode.val);
            listNode = listNode.next;
        }
    }
}
